<?php if (!defined('NOVA_RUN')) die('You can\'t access this file directly!');

/*
-------------------------------------------------------
*
*   NovaBoard 2
*   Copyright © 2011 NovaBoard team
*
*--------------------------------------------------------
*
*   Official site: www.novaboard.net
*   Contact e-mail: support@novaboard.net
*
*   GNU General Public License, version 2:
*   http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/

abstract class Engine
{
	function __construct()
	{
	}

	// static alias for 
	public static function initEngine()
	{
		if (!class_exists('db', false))
		{
			// load db
			self::load_db();
		}

		// load config
		self::load_config();
	}

	// load database class
	private static function load_db()
	{
		// Load config file
		require ROOT . 'engine/db/db_config.php';
		
		// Load classes
		require ROOT . 'engine/db/db_statement.php';
		require ROOT . 'engine/db/nova_db.php';
		require ROOT . 'engine/db/drivers/driver_' . $db_config['db_type'] . '.php';
		
		$db = db::instance($db_config);
		$db->setEncoding();
	}

	// load configuration from database
	private static function load_config()
	{
		$config = Config::load();
		
		if (empty($config))
		{
			$query = db::instance()->select('cacheSettings', array
			(
				'fields' => array('name', 'value'),
				'tables' => 'settings'
			), true);
			
			foreach ($query as $row)
			{
				$config[$row['name']] = $row['value'];
			}
			
			Cache::save('config', $config);
		}
		
		Config::add($config);
	}

	// use this method to show user 404 NOT FOUND page
	public static function not_found()
	{
		header('HTTP/1.1 404 Not Found'); 	
		tpl::instance()->show('err_404');
		ob_end_flush();
		exit;
	}

	// use this method to show user some error page
	protected static function showError($errCode)
	{
		redirect(make_link('error', 'view', array($errCode)));
	}

	public static function secretKey($key = false)
	{
		if (!@$_SESSION['secret_key']) $_SESSION['secret_key'] = make_rand(32);

		if ($key !== false)
		{
			if ($_SESSION['secret_key'] != get_request('secretKey', 'post')) throw new Exception('Secret key is corrupt!');
			else return false;
		}
		else
		{
			return $_SESSION['secret_key'];
		}
	}
}